package com.bdqn.controller;

import com.bdqn.entity.role;
import com.bdqn.entity.user;
import com.bdqn.service.smbms_roleService;
import com.bdqn.service.smbms_userService;
import com.bdqn.util.page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("/user")
public class Usercontroller {
    @Autowired
    private smbms_userService user;
    @Autowired
    private smbms_roleService ro;

    @RequestMapping("/getUserAll")
    public String getUserAll(Integer currentPageNo , HttpServletRequest request, Integer queryUserRole, String queryname){
        //全部用户集合
        List<user> userList = null;
        List<role> reloList = ro.findAllrole();

        if (currentPageNo == null) {
            currentPageNo=1;
        }

        Map map = new HashMap();
        map.put("currentPageNo",(currentPageNo-1)*10);
        map.put("queryUserRole",queryUserRole);
        map.put("queryUserName",queryname);
        map.put("pageSize",10);

        page pa = new page();
        pa.setPageSize(10);
        pa.setTotalCount(user.getAllCount(map));
        pa.setCurrentPageNo(currentPageNo);

        userList = user.getAlluserBynames(map);
        request.getSession().setAttribute("userList",userList);
        request.getSession().setAttribute("page",pa);
        request.getSession().setAttribute("roleList",reloList);
        request.getSession().setAttribute("queryUserRole",queryUserRole);
        request.getSession().setAttribute("queryUserName",queryname);
        return "redirect:/userlist.jsp";
    }
    @RequestMapping("/Login.do")
    public void Login(@RequestParam String userCode , @RequestParam String userPassword , HttpServletResponse response, HttpServletRequest request) throws IOException {
        user login = user.Login(userCode,userPassword);
        if (login != null){
            request.getSession().setAttribute("user",login);
            response.sendRedirect(request.getContextPath()+"/frame.jsp");
        }else {
            System.out.println(login+"===================================2");
            request.getSession().setAttribute("error","账号或者密码输入错误！！");
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }

    }

    @RequestMapping("/addUser")
    public String addUser(@ModelAttribute user u, @RequestParam("attachs") MultipartFile[] files , HttpServletRequest request) throws IOException {
        String filename = null;
        System.out.println(files.length);
        String path = null;
        if (files != null) {
            path = request.getSession().getServletContext().getRealPath("/imges");
            for (int i = 0; i < files.length; i++) {
                // 创建File对象，一会向该路径下上传文件
                File file = new File(path); // 判断路径是否存在，如果不存在，创建该路径
                if (!file.exists()) {
                    file.mkdirs();
                }
                // 获取到上传文件的名称
                System.out.println("表单的name"+files[i].getName());
                filename = files[i].getOriginalFilename();  //获取上传的文件名
                String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
                // 把文件的名称唯一化
                filename =File.separator+uuid + "_" + filename;
                // 上传文件
                files[i].transferTo(new File(file, filename));

            }
        }
        u.setIDPICPATH(path+filename);
        user us = (user) request.getSession().getAttribute("user");
        u.setCreatedBy(us.getId());
        u.setCreationDate(new Date());
        int i = user.addUser(u);
        return "redirect:/user/getUserAll";
    }

    @RequestMapping("/delUser")
    public void delUser(Integer id,HttpServletResponse response) throws IOException {
        if (user.delUser(id)>0){
            response.getWriter().print("true");
        }else {
            response.getWriter().print("flase");
        }
    }

    @RequestMapping("/getUser/{id}")
    public String getUser(@PathVariable(value = "id") Integer id, HttpServletRequest request, String opr){
        user user1 = this.user.getUser(id);
        request.getSession().setAttribute("user",user1);
        if (opr.equals("usermodify")){
            request.getSession().setAttribute("id",id);
        }
        return "redirect:/"+opr+".jsp";

    }
    @RequestMapping("/updUser")
    public String updUser(@Valid user u, BindingResult result, HttpServletRequest request, Model model){
        if (result.hasErrors()){   //判断数据是否符合规定
            System.out.println(result.getAllErrors().toString());
            model.addAttribute("user",u);
            return "forward:/usermodify.jsp";
        }
        Integer id = (Integer) request.getSession().getAttribute("id");
        u.setId(id);
        System.err.println(id);
        user.updUser(u);
        return "redirect:/user/getUserAll";
    }
    @RequestMapping("/logout.html")
    public String logingOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        request.getSession().removeAttribute("error");
        return "redirect:/login.jsp";
    }

    @RequestMapping("/download")
    public String download(HttpServletRequest request, HttpServletResponse response){
        String fileName = "59D1EB7BDE34466DA6E6B8655A187201_img111111.jpg";
        if (fileName != null) {
            String realPath = request.getRealPath("/");
            File file = new File(realPath + "imges", fileName);
            if (file.exists()) {
                response.setContentType("application/force-download"); // 响应类型
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    @RequestMapping("/pwdmodify")
    public String pwdmodify(String method , String oldpassword , String newpassword, HttpServletRequest request, HttpServletResponse response) throws IOException {
        user u = (user)request.getSession().getAttribute("user");
        if (u != null) {
            user.updPwd(u.getId(), newpassword);
            request.getSession().setAttribute("error", "密码已修改，请重新登录！！");
        }
        return  "redirect:/login.jsp";
    }

    @RequestMapping("/checkPwd")
    public void checkPwd(String oldpassword, HttpServletResponse response, HttpServletRequest request) throws IOException {
        user u = (user)request.getSession().getAttribute("user");
        if (u!= null) {
            if (oldpassword.equals(u.getUserPassword())) {
                response.getWriter().print("true");
            } else {
                response.getWriter().print("false");
            }
        }
    }


}
